<template>
<div id="teamAddPage">
  <van-form @submit="onSubmit">
    <div class="center">
      <van-uploader :after-read="afterRead"
                    :max-count="1"
                    :max-size="5 * 1024 * 1024"
                    @oversize="onOversize">
        <div>
          <img class="img" :src="addTeamData?.teamAvatarUrl ? addTeamData.teamAvatarUrl :defaultPicture ">
        </div>
      </van-uploader>
    </div>
    <van-cell-group inset>
      <van-field
          v-model="addTeamData.name"
          name="name"
          label="队伍名称"
          placeholder="请输入队伍名称"
          :rules="[{ required: true, message: '输入队伍名称' }]"
      />
      <van-field
          v-model="addTeamData.description"
          type="textarea"
          row="4"
          autosize
          name="description"
          label="队伍描述"
          placeholder="请输入队伍描述"
      />
<!--      过期时间-->
      <van-field
          is-link
          readonly
          name="dataPicker"
          label="时间选择"
          :placeholder="addTeamData.expireTime ?? '点击选择队伍过期时间'"
          @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-date-picker
            @confirm="onConfirm"
            @cancel="showPicker = false"
            type="datetime"
            title="请选择过期时间"
            :min-data ="minDate"
        />
      </van-popup>
      <van-field name="stepper" label="最大人数">
        <template #input>
          <van-stepper v-model="addTeamData.maxNum" max="10" min="3"/>
        </template>
      </van-field>
      <van-field name="radio" label="队伍状态">
        <template #input>
          <van-radio-group v-model="addTeamData.status" direction="horizontal">
            <van-radio name="0">公开</van-radio>
            <van-radio name="1">私有</van-radio>
            <van-radio name="2">加密</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
          v-if="Number(addTeamData.status) === 2"
          v-model="addTeamData.password"
          type="password"
          name="Password"
          label="密码"
          placeholder="请输入队伍密码"
          :rules="[{ required: true, message: '请填写密码' }]"
      />

    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
  <div class="updateAvatarUrl" v-if="updateAvatarUrl">
    <van-loading color="#0094ff" size="10">头像更新中...</van-loading>
  </div>
</div>
</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import moment from "moment";
import myAxios from "../plugins/myAxios.js";
import {showFailToast, showNotify, showSuccessToast} from "vant";
import {onMounted, ref} from "vue";
import {defaultPicture} from "../common/userCommon.ts"


const router = useRouter();

//日期展示器
const showPicker = ref(false);
//当前时间
const minDate = new Date();
const updateAvatarUrl = ref(false)


const onConfirm = ({selectedValues}) =>{
  addTeamData.value.expireTime = selectedValues.join("-");
  showPicker.value = false;

  //console.log(selectedValues);
}



const initFromData ={
  "teamAvatarUrl":"",
  "name": "",
  "description": "",
  "expireTime": null,
  "maxNum": 5,
  "password": "",
  "status": 0,
}

//需要用户填写的表单数据 对象扩展
const addTeamData = ref({...initFromData})


//提交
const onSubmit = async() => {
  const postData ={
    ...addTeamData.value,
    status: Number(addTeamData.value.status),
    expireTime: moment(addTeamData.value.expireTime).format("YYYY-MM-DD HH:mm:ss")
  }
  const res  =await myAxios.post("/team/add",postData);
  if(res?.code === 0 && res.data) {
    showSuccessToast('添加成功');
    router.push({
      path: '/team',
      replace: true,
    });
  }else{
    showFailToast('添加失败');

  }
}



const show_TeamAvatarUrl_pop = ref("true")

onMounted(() => {
  const show_teamCreateAvatarUrl = sessionStorage.getItem("teamCreateAvatarUrl")
  show_TeamAvatarUrl_pop.value = show_teamCreateAvatarUrl ? show_teamCreateAvatarUrl : show_TeamAvatarUrl_pop.value
  if (show_TeamAvatarUrl_pop.value === "true") {
    showNotify({message: '点击默认头像可更换队伍头像', type: "primary", duration: 2000});
    show_TeamAvatarUrl_pop.value = "false"
    sessionStorage.setItem('teamCreateAvatarUrl', show_TeamAvatarUrl_pop.value)
  }
})

const afterRead = async (file: any) => {
  updateAvatarUrl.value = true
  if(updateAvatarUrl.value){
    const teamAvatarUrl = await myAxios.post("/file/upload", {
      'file': file.file,
      'biz': "team_avatar"
    }, {
      headers: {'Content-Type': 'multipart/form-data'},
    })
    addTeamData.value.teamAvatarUrl =teamAvatarUrl.data
    if (teamAvatarUrl.data)
      setTimeout(() => {
        updateAvatarUrl.value = false
      }, 1300);
  }
};

const onOversize = () => {
  showFailToast("头像上传大小不能超过5mb")
}
</script>

<style scoped>
.updateAvatarUrl {
  position: fixed;
  top: 30%;
  left: 37%;
}

.center {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.img {
  box-shadow: 0 0 14px rgba(0, 0, 0, 0.5);
  border-radius: 20%;
  height: 135px;
  width: 135px;
}
</style>